//
//  WBNetworkManager.swift
//  迷你微博
//
//  Created by Json on 2020/3/6.
//  Copyright © 2020 Json. All rights reserved.
//

import UIKit
import AFNetworking

// swift 的枚举支持c任何数据类型
enum WBHTTPMethod {
    case GET
    case POST
}

// 网络管理工具
class WBNetworkManager: AFHTTPSessionManager {

    // 静态区/常量/闭包
    // 在第一次访问时，执行闭包，并且将结果保存在 shared 常量中
    static let shared = WBNetworkManager()
        
    /// 封装 get/post 请求
    /// - Parameters:
    ///   - method: GET / POSt
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调 [json (字典 / 数据)，是否成功]
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: Any], completion: @escaping (_ json: Any?, _ isSuccess: Bool)->())  {
        
        let success = { (task: URLSessionDataTask, json: Any?) -> () in
            completion(json,true)
        }
        let failure = { (task: URLSessionDataTask?, error: Error) -> () in
            print("网络请求错误 \(error)")
            completion(nil,false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
